package cn.tedu.ivos2.base.file;

import cn.tedu.ivos2.base.response.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1/file")
public class UploadController {

    @Value("${image_path}")
    private String image_path;

    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        String filenName  = file.getOriginalFilename();
        String suffix = filenName.substring(filenName.lastIndexOf("."));
        filenName = UUID.randomUUID() + suffix;
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        File dirFile = new File(image_path + datePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String filePath = image_path + datePath + filenName;
        file.transferTo(new File(filePath));
        return JsonResult.ok(datePath + filenName);
    }
    @PostMapping("remove")
    public JsonResult remove(String imageUrl) {
        new File(image_path + imageUrl).delete();
        return JsonResult.ok();
    }
}
